package com.mzj.saas.mservice.sys.service;

import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.CustomFieldManagement;
import com.mzj.saas.mservice.department.entity.CustomFieldValue;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.FieldStatusRef;
import com.mzj.saas.mservice.department.repository.CustomFieldManagementRepository;
import com.mzj.saas.mservice.department.repository.CustomFieldValueRepository;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.repository.FieldStatusRefRepository;
import com.mzj.saas.mservice.department.service.DepartmentService;
import com.mzj.saas.mservice.department.vo.CustomFieldManagementVO;
import com.mzj.saas.redis.RedisService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class FieldService {
    private static final Logger LOG = LoggerFactory.getLogger(FieldService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CustomFieldManagementRepository customFieldManagementRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private CustomFieldValueRepository customFieldValueRepository;
    @Autowired
    private FieldStatusRefRepository fieldStatusRefRepository;

    /*
     *显示通讯录字段
     */
    public ResultBean<Object> companyFieldList(String accessToken) {
        LOG.info("---FieldService companyFieldList accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            ResultBean<Object> objectResultBean = departmentService.addDepartmentFieldList(accessToken);
            if (objectResultBean.getResultData() != null) {
                List<Map<String, Object>> maps = (List<Map<String, Object>>) objectResultBean.getResultData();
                maps.forEach(m -> {
                    Object fieldName = m.get("fieldName");
                    CustomFieldManagement existCustomField = customFieldManagementRepository.findByFieldNameAndOrgId(String.valueOf(fieldName), tokenRedisVo.getEnterpriseId());
                    if (existCustomField == null) {
                        //标识默认字段
                        m.put("flag", 0);
                    } else {
                        m.put("flag", 1);
                    }
                });
                result.setResultData(maps);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *新增自定义字段
     */
    @Transactional
    public ResultBean<Object> addCompanyField(String accessToken, String name) {
        LOG.info("---FieldService addCompanyField accessToken={},name={}", accessToken, name);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(name)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            String fieldName = pinyin(name);
            Optional<Department> existDepartment = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartment == null) {
                return ResultBean.failedResultWithMsg("部门不存在或已删除");
            }
            CustomFieldManagement existCustomField = customFieldManagementRepository.findByNameAndOrgId(name, tokenRedisVo.getEnterpriseId());
            if (existCustomField != null) {
                return ResultBean.failedResultWithMsg("该字段已存在");
            }
            CustomFieldManagementVO customFieldManagementVO = new CustomFieldManagementVO();
            customFieldManagementVO.setName(name);
            customFieldManagementVO.setOperatorId(tokenRedisVo.getId());
            customFieldManagementVO.setMustStatus(1);
            customFieldManagementVO.setShowStatus(1);
            customFieldManagementVO.setOrgId(tokenRedisVo.getEnterpriseId());
            customFieldManagementVO.setLastUpdateTime(new Date());
            customFieldManagementVO.setFieldName(fieldName);
            customFieldManagementVO.setCreateTime(new Date());
            customFieldManagementVO.setUpdateUserId(tokenRedisVo.getId());
            result.setResultData(customFieldManagementVO);
            CustomFieldManagement customFieldManagement = new CustomFieldManagement();
            BeanUtils.copyProperties(customFieldManagementVO, customFieldManagement);
            customFieldManagementRepository.save(customFieldManagement);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *获取中文的拼音
     */
    public String pinyin(String name) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = name.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (Character.toString(arr[i]).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                    if (temp != null) {
                        for (String s : temp) {
                            pybf.append(s);
                        }
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    /*
     *删除自定义字段
     */
    @Transactional
    public ResultBean<Object> deleteCompanyField(String accessToken, Long id) {
        LOG.info("---FieldService addCompanyField accessToken={},id={}", accessToken, id);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (id == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            Optional<Department> existDepartment = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartment == null) {
                return ResultBean.failedResultWithMsg("部门不存在或已删除");
            }
            List<CustomFieldValue> existUserFieldValue = customFieldValueRepository.findByFieldId(id);
            //主管理员有权限直接删除字段  【masterStatus: 是否主管理员 1.是 0.否】
            if(tokenRedisVo.getMasterStatus().longValue() == 0) {
                if (existUserFieldValue != null && existUserFieldValue.size() != 0) {
                    return ResultBean.failedResultWithMsg("字段下存在用户信息无法删除");
                }
            }
            customFieldManagementRepository.deleteById(id);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *修改显示状态
     */
    @Transactional
    public ResultBean<Object> updateFieldShowStatus(String accessToken, Long flag, Long id, Integer status) {
        LOG.info("---FieldService updateFieldShowStatus accessToken={},flag={},id={},status={}", accessToken, flag, id, status);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (id == null || flag == null || status == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            Optional<Department> existDepartment = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartment == null) {
                return ResultBean.failedResultWithMsg("部门不存在或已删除");
            }
            //默认字段
            if (flag == 0) {
                FieldStatusRef existFieldStatusRef = fieldStatusRefRepository.findByOrgIdAndDefaultFieldId(tokenRedisVo.getEnterpriseId(), id);
                if (existFieldStatusRef == null) {
                    return ResultBean.failedResultWithMsg("字段信息不存在或已删除");
                }
                existFieldStatusRef.setShowStatus(status);
                existFieldStatusRef.setUpdateUserId(tokenRedisVo.getId());
                existFieldStatusRef.setLastUpdateTime(new Date());
                existFieldStatusRef.setLastUpdateTime(new Date());
                fieldStatusRefRepository.save(existFieldStatusRef);
            } else {
                Optional<CustomFieldManagement> existCustomFieldManagementOptional = customFieldManagementRepository.findById(id);
                if (existCustomFieldManagementOptional == null) {
                    return ResultBean.failedResultWithMsg("字段信息不存在或已删除");
                }
                CustomFieldManagement customFieldManagement = existCustomFieldManagementOptional.get();
                customFieldManagement.setShowStatus(status);
                customFieldManagement.setUpdateUserId(tokenRedisVo.getId());
                customFieldManagement.setLastUpdateTime(new Date());
                customFieldManagement.setLastUpdateTime(new Date());
                customFieldManagementRepository.save(customFieldManagement);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *修改必填状态
     */
    @Transactional
    public ResultBean<Object> updateFieldMustStatus(String accessToken, Long flag, Long id, Integer status) {
        LOG.info("---FieldService updateFieldMustStatus accessToken={},flag={},id={},status={}", accessToken, flag, id, status);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (id == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            Optional<Department> existDepartment = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartment == null) {
                return ResultBean.failedResultWithMsg("部门不存在或已删除");
            }
            //默认字段
            if (flag == 0) {
                FieldStatusRef existFieldStatusRef = fieldStatusRefRepository.findByOrgIdAndDefaultFieldId(tokenRedisVo.getEnterpriseId(), id);
                if (existFieldStatusRef == null) {
                    return ResultBean.failedResultWithMsg("字段信息不存在或已删除");
                }
                existFieldStatusRef.setMustStatus(status);
                existFieldStatusRef.setUpdateUserId(tokenRedisVo.getId());
                existFieldStatusRef.setLastUpdateTime(new Date());
                existFieldStatusRef.setLastUpdateTime(new Date());
                fieldStatusRefRepository.save(existFieldStatusRef);
            } else {
                Optional<CustomFieldManagement> existCustomFieldManagementOptional = customFieldManagementRepository.findById(id);
                if (existCustomFieldManagementOptional == null) {
                    return ResultBean.failedResultWithMsg("字段信息不存在或已删除");
                }
                CustomFieldManagement customFieldManagement = existCustomFieldManagementOptional.get();
                customFieldManagement.setMustStatus(status);
                customFieldManagement.setUpdateUserId(tokenRedisVo.getId());
                customFieldManagement.setLastUpdateTime(new Date());
                customFieldManagement.setLastUpdateTime(new Date());
                customFieldManagementRepository.save(customFieldManagement);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
